import WebUploader from 'webuploader/dist/webuploader.js';
import PaBaseModel from '../../core/model/PaBaseModel';

function workerInfoDetailCtrl($scope, $http, ngDialog, paFetchService, $interval, ngDialogTechTraining) {
  'ngInject';

  let id = $state.params.id;

  this.editable = false; // 基本信息处于不可编辑状态

  this.userInfo = {};

  // 专业技术data
  this.proItemList = {};

  // 教育培训data
  this.eduItemList = {};

  // 安全技术交底
  // 分布分项
  this.distributionItemList = {};

  // 工种
  this.workItemList = {};

  // 简历
  this.resumeItemList = {};

  // 获得头像src
  this.getAvatarSrc = () => {
    if (this.userInfo && this.userInfo.imageFile && this.userInfo.imageFile.filePath) {
      let src = `${SERVER_IP}/${this.userInfo.imageFile.filePath}`;
      return src;
    } else {
      return require('../../../assets/images/' + 'timg.jpg');
    }
  };

  // 文件下载
  this.getDownloadSrc = (file) => {
    return `${HOST_URL}${SERVER_CONTEXT}/api/safesite/workerInfo/download/${file.id}`;
  }

  // 获取人员详情-基本信息，专业技术，简历
  this.workerInfoInit = () => {
    var url = `${SERVER_CONTEXT}/api/safesite/workerInfo/selectByPrimaryKey/${id}`;
    $http.get(url)
      .then((resp) => {       
        if(resp.statusText == 'OK'){
          this.userInfo = resp.data; // 基本信息
          this.editableUserInfo = new PaBaseModel(this.userInfo); // 可编辑基本信息数据
          this.fileItemList = resp.data.fileBeanList;

          // 判断页面特种人员的状态
          if(this.userInfo.isspecialMan == '1'){
            this.isSpecialMandatory = true; // 特种人员显示证书编号等为必填
          }else {
            this.isSpecialMandatory = false;
          }

          this.proItemList = resp.data.workerSkillList; // 专业技术数据
          this.editableProItemList = []; // 可编辑专业技术数据
          this.proItemList.forEach((item) => {
            this.editableProItemList.push(new PaBaseModel(item));
          });

          this.resumeItemList = resp.data.workerResumeList; // 简历数据
          this.editableResumeItemList = []; // 可编辑简历数据
          this.resumeItemList.forEach((item) => {
            this.editableResumeItemList.push(new PaBaseModel(item));
          });
        }              
    });
  };

  // 获取岗位类别
  this.getJobCategory = () => {
    $http.get(`${SERVER_CONTEXT}/api/organization/queryDictionaryListByType/岗位类别`).
      then((resp) => {
        if(resp.statusText == 'OK'){
          this.categoryList = resp.data;
        }
    });
  }

  // 获取作业类别
  this.getWorkCategory = () => {
    $http.get(`${SERVER_CONTEXT}/api/organization/queryDictionaryListByType/作业类别`).
      then((resp) => {
        if(resp.statusText == 'OK'){
          this.workList = resp.data;
        }
    });
  }

  // 获得施工队list             
  paFetchService
                .getTeamWithOrgList()
                .then((resp) => {
                  this.teamWithOrgList = resp.data;
                });

  // 文件预览
  this.preview = (archiveDetail) => {
    let url = $state.href('documentPreview', {
      id: archiveDetail.id,
    });
    window.open(url,'_blank');
  }

  // 获取人员详情-教育培训
  this.workerInfoTechInit = () => {
    var url = `${SERVER_CONTEXT}/api/education/queryEducationInfos`;
    let reqData = {
      trainType : '1',
      workerId: id
    }
    $http.post(url,reqData)
      .then((resp) => {
        if(resp.statusText == 'OK'){
          this.eduItemList = resp.data; // 教育培训
        }       
    });
  }

  // 获取教育培训主题列表
  this.educationTopicsList = () => {
    let respData = {
      trainType:'1'
    }
    $http.post(`${SERVER_CONTEXT}/api/education/queryAllEducationItem`,
      respData).
        then((resp) => {
          if(resp.statusText == 'OK'){
            this.topicList = resp.data;
          }       
      });
  }

  // 查看教育培训 安全交底
  this.queryDisclosure = (id) => {
    ngDialogTechTraining
      .confirm(id);
  }

  // 获取人员详情-安全技术交底-分布分项1
  this.workerInfoSafeInit = (param) => {
    var url = `${SERVER_CONTEXT}/api/education/queryEducationInfos`;
    let reqData = {
      workerId: id,
      trainType : '2',
      jdType : '1' // 交底类型-分布分项
    }
    $http.post(url,reqData)
      .then((resp) => {
        this.distributionItemList = resp.data;       
    });
  }

  // 获取人员详情-安全技术交底-工种2
  this.workerInfoWorkerInit = (param) => {
    var url = `${SERVER_CONTEXT}/api/education/queryEducationInfos`;
    let reqData = {
      workerId: id,
      trainType : '2',
      jdType : '2' // 交底类型-工种
    }
    $http.post(url,reqData)
      .then((resp) => {
        this.workItemList = resp.data;
    });
  }

  // 获取安全技术交底- 分布分项-主题
  this.safetyTechnicalDisclosure = () => {
    let respData = {
      trainType:'2',
      jdType:'1'
    }
    $http.post(`${SERVER_CONTEXT}/api/education/queryAllEducationItem`,
      respData).
        then((resp) => {
          if(resp.statusText == 'OK'){
            this.safeDistributionList = resp.data;
          }       
      });
  }

  // 获取安全技术交底- 工种-主题
  this.safetyWorkerTitle = () => {
    let respData = {
      trainType:'2',
      jdType:'2'
    }
    $http.post(`${SERVER_CONTEXT}/api/education/queryAllEducationItem`,
      respData).
        then((resp) => {
          if(resp.statusText == 'OK'){
            this.safeWorkerList = resp.data;
          }       
      });
  }

  // 基本信息
  // 编辑基本信息
  this.editInfo = () => {
    // 取消编辑
    if (!this.editable) {
      this.editableUserInfo.$reset();
    }
    this.editable = !this.editable;
  };

 
  // 是否是特种人员 input change事件
  this.isSpecial = () => {
    if(this.editableUserInfo.isspecialMan == '1'){
      this.isSpecialMandatory = true; // 特种人员显示证书编号等为必填
    }else {
      this.isSpecialMandatory = false;
    }
  }

  // 保存基本信息
  this.save = (param) => { 
    // 修改表单是否提交过状态
    param.$submitted = true;

    // 表单校验
    if (param.$invalid) {
      return false;
    }
    this.editableUserInfo.fileIds = this.editableUserInfo.fileBeanList.map((item) =>{
      return item.id;
    });
    delete this.editableUserInfo.entryTime;
    $http.put(`${SERVER_CONTEXT}/api/safesite/workerInfo/updateRecord`,
      this.editableUserInfo).
      then((resp) => {
        if(resp.data.success){
          $scope.workerInfoDetail.editableUserInfo.$sync();         
          this.editable = false;
          $state.reload();
        } else {
          layer.alert('错误');
        }
    });
  };

  // 重置基本信息
  this.reset = () => {
    this.editableUserInfo.$reset();
  };

  // 专业技术
  // 新增专业技术
  this.addProSkill = () => {
    this.isAddible = !this.isAddible;
  };

  //编辑专业技术professional
  this.editProfessional = (item) => {
    item.isEditable = true;
  };

  this.list = [];
  // 编辑保存专业技术item
  this.saveProSkillItem = (item, index) => { 
    item.isEditable = false;
    this.editableProItemList[index].$sync();    
    this.list = item;
    this.list.workerId = id;
    $http.put(`${SERVER_CONTEXT}/api/safesite/workerSkill/updateByPrimaryKeySelective`,
      this.list).
      then((resp) => {           
        if (resp.data.success) {
          layer.msg(resp.data.message);
        } else {
          layer.alert(resp.data.message);
        }
      });
  };

  //删除专业技术
  this.detete = (id) => {
    let _this = this;
    $scope.modalTitle = '删除专业技术';
    $scope.modalContent = '确认要删除该信息吗?';
    ngDialog.openConfirm({
    template: 'paConfirm',
    className: 'ngdialog-theme-default pa-confirm-theme',
    scope: $scope,
    }).
      then((value) => {
        $http.delete(`${SERVER_CONTEXT}/api/safesite/workerSkill/deleteByPrimaryKey/${id}`).
          then((resp) => {
            if (resp.data.success) {
              layer.msg(resp.data.message);
              this.workerInfoInit();              
            } else {
              layer.alert(resp.data.message);
            }          
          });
      }, (reason) => {});
  };

  // 取消编辑专业技术
  this.cancelEditSkill = (item, index) => {
    this.editableProItemList[index].$reset();
    item.isEditable = false;
  };

  this.addSkillList = {};
  // 增加保存专业技术
  this.addSkill = (param) => {
    // 修改表单是否提交过状态
    param.$submitted = true;

    // 表单校验
    if (param.$invalid) {
      return false;
    }

    this.addSkillList.workerId = id;
    $http.post(`${SERVER_CONTEXT}/api/safesite/workerSkill/insertSelective`,
      this.addSkillList).
      then((resp) => {  
        if (resp.data.success) {
          this.proItemList.push(this.addSkillList);            
          this.addSkillList = {}; 
          this.workerInfoInit();
        }           
    });
  };

  // 取消增加专业技能
  this.cancelAddSkill = () => {
    this.addSkillList = {};
    this.isAddible = false;
  };
  
  // 教育培训
  // 新增教育培训,取消新增
  this.addTech = () => {
    this.isAddTech = !this.isAddTech;
  }

  //删除教育培训
  this.techDetete = (item,index) => {
    let _this = this;
    $scope.modalTitle = '删除教育培训';
    $scope.modalContent = '确认要删除该信息吗?';
    ngDialog.openConfirm({
    template: 'paConfirm',
    className: 'ngdialog-theme-default pa-confirm-theme',
    scope: $scope,
    }).
      then((value) => {
        $http.delete(`${SERVER_CONTEXT}/api/education/deleteEducationInfoByWorker/${item.educationTrainId}/${id}`).
          then((resp) => {
            if (resp.data.success) {
              layer.msg(resp.data.message);
              this.workerInfoTechInit();
            } else {
              layer.alert(resp.data.message);
            }                     
          });
      }, (reason) => {});
  }

  // 新增教育培训列表item
  this.addTechEdu = (param) => {  

    if (param.type.$invalid) {
      layer.alert('请选择标题');
      return false;
    }

    let respData = { 
      workerId: id,
      workerName: this.userInfo.name,
      constructionTeamId: this.userInfo.constructionTeamId,
      educationTrainId: this.educationTraningList.id,
      checked:'1'
    }
    $http.post(`${SERVER_CONTEXT}/api/education/insertEducationInfoByWorker`,
      respData).
      then((resp) => { 
        if(resp.data.success){
          layer.msg(resp.data.message);
          this.isAddTech = false;
          this.workerInfoTechInit();
        } else if (!resp.data.success) {
          layer.alert(resp.data.message);
          return false;
        }               
    });
  };

  // 取消新增教育培训
  this.cancelAddTech = () => {
    this.isAddTech = false;
  };

  // 新增安全技术交底/分布分项/工种
  this.safeTech = () => {
    this.isAddSafe = !this.isAddSafe;
    if(this.typeofWork){
      this.isWorker = true;
      this.isDistribution = false;
    }else {
      this.isDistribution = true;
      this.isWorker = false;
    }
  }

  // 显示安全技术交底--分布分项
  this.distribution = () => {
    this.typeofWork = false;
    if(this.isWorker){
      this.isWorker = false;
      this.isDistribution = true;
    }
  } 

  // 删除安全技术交底--分布分项
  this.safeDetete = (param) => {
    let _this = this;
    $scope.modalTitle = '删除分布分项';
    $scope.modalContent = '确认要删除该信息吗?';
    ngDialog.openConfirm({
    template: 'paConfirm',
    className: 'ngdialog-theme-default pa-confirm-theme',
    scope: $scope,
    }).
      then((value) => {
        $http.delete(`${SERVER_CONTEXT}/api/education/deleteEducationInfoByWorker/${param.educationTrainId}/${id}`)
          .then((resp) => {
            if (resp.data.success) {
              layer.msg(resp.data.message);
              $state.reload();
            } else {
              layer.alert(resp.data.message);
            }
          });
      }, (reason) => {});
  };

  // 显示安全技术交底--工种
  this.profession = () => {
    this.typeofWork = true;
    if(this.isDistribution){
      this.isWorker = true;
      this.isDistribution = false;
    }
  };

  // 删除安全技术交底--工种
  this.workDetete = (param) => {
    let _this = this;
    $scope.modalTitle = '删除工种';
    $scope.modalContent = '确认要删除该信息吗?';
    ngDialog.openConfirm({
    template: 'paConfirm',
    className: 'ngdialog-theme-default pa-confirm-theme',
    scope: $scope,
    }).
      then((value) => {
        $http.delete(`${SERVER_CONTEXT}/api/education/deleteEducationInfoByWorker/${param.educationTrainId}/${id}`).
          then((resp) => {
            if (resp.data.success) {
              layer.msg(resp.data.message);
              $state.reload();
            } else {
              layer.alert(resp.data.message);
            }
          });
      }, (reason) => {});
  };

  // 新增安全技术交底-分布分项
  this.addSafeDistribution = (param) => {
    
    if (param.safeName.$invalid) {
      layer.alert('请选择相关标题');
      return false;
    }

    let respData = {      
      workerId: id,
      workerName: this.userInfo.name,
      constructionTeamId: this.userInfo.constructionTeamId,
      educationTrainId: this.safetyTechnicalList.safeName.id,
      jdType: '1',
      checked:'1'
    }
    $http.post(`${SERVER_CONTEXT}/api/education/insertEducationInfoByWorker`,
      respData).
      then((resp) => {    
        if (resp.data.success) {
          layer.msg(resp.data.message);
          this.workerInfoSafeInit(); 
        } else if (!resp.data.success) {
          layer.alert(resp.data.message);
        }   
    });
  }

  // 新增安全技术交底-工种
  this.addSafeCategory = (param) => {
    if (param.topic.$invalid) {
      layer.alert('请选择标题');
      return false;
    }

    let respData = {      
      workerId: id,
      workerName: this.userInfo.name,
      constructionTeamId: this.userInfo.constructionTeamId,
      educationTrainId: this.safetyTechnicalList.safeName.id,
      jdType: '2',
      checked:'1'
    }
    $http.post(`${SERVER_CONTEXT}/api/education/insertEducationInfoByWorker`,
      respData).
      then((resp) => {    
        if(resp.data.success){
          layer.msg(resp.data.message);
          this.workerInfoWorkerInit();                   
        } else if (!resp.data.success) {
          layer.alert(resp.data.message);
        }   
    });
  }

  // 取消新增安全技术交底 -分布分项
  this.cancelDistribution = () => {
    this.isDistribution = false;
    this.isAddSafe = false;
  }

  // 取消新增安全技术交底 -工种
  this.cancelSafe = () => {
    this.isWorker = false;
    this.isAddSafe = false;
  }

  // 简历
  // 编辑简历
  this.editResume = (item) => {
    item.resume = true;     
  };

  // 删除简历item
  this.resumeDetete = (id) => {
    let _this = this;
    $scope.modalTitle = '删除简历';
    $scope.modalContent = '确认要删除该信息吗?';
    ngDialog.openConfirm({
    template: 'paConfirm',
    className: 'ngdialog-theme-default pa-confirm-theme',
    scope: $scope,
    }).
      then((value) => {
        $http.delete(`${SERVER_CONTEXT}/api/safesite/workerResume/deleteByPrimaryKey/${id}`).
          then((resp) => {
            if (resp.data.success) {
              this.workerInfoInit();
            } else {
              layer.alert(resp.data.message);
            }           
          });
      }, (reason) => {});
  };

  // 保存编辑简历item
  this.saveResumeItem = (item,index,param) => {
    if (!param.startTime.$invalid && param.endTime.$invalid) {
      layer.alert('请填写简历结束时间');
      return false;
    } else if (param.startTime.$invalid && !param.endTime.$invalid) {
      layer.alert('请填写简历开始时间');
      return false;
    } else if (param.startTime.$valid && param.endTime.$valid) {
      if (param.startTime.$viewValue < param.endTime.$viewValue) {
        this.editSaveResume(item,index);
        return false;
      } else {
        layer.alert('开始时间应小于结束时间');
      }
    } else {
      this.editSaveResume(item,index);
    }
  }

  this.editSaveResume = (item,index) => {
    item.resume = false;
    this.editableResumeItemList[index].$sync();    
    this.resumeList = item;
    this.resumeList.workerId = id;
    $http.post(`${SERVER_CONTEXT}/api/safesite/workerResume/updateByPrimaryKeySelective`,
      this.resumeList).
      then((resp) => {           
        this.workerInfoInit();
      });
  }

  // 取消编辑简历
  this.cancelEditResume = (item,index) => {
    this.editableResumeItemList[index].$reset();
    item.resume = false;
  };

  // 新增简历
  this.addResume = () => {
    this.isAddResume = !this.isAddResume;
  };

  this.addResumeList = {}; // 新增的简历item

  // 保存新增简历
  this.addSaveResume = (param) => {
    if (param.startTime.$invalid) {
      layer.alert('请填写简历开始时间');
      return false;
    } else if (param.endTime.$invalid) {
      layer.alert('请填写简历结束时间');
      return false;
    } else if (param.startTime.$valid && param.endTime.$valid) {
        if (param.startTime.$viewValue < param.endTime.$viewValue) {        
          if (param.projectExperience.$invalid) {
            layer.alert('请填写简历经历');
            return false;
          } else {
            this.getAddResume();
            return false;
          }
        } else {
          layer.alert('开始时间应小于结束时间');
          return false;
        }
    }
    this.getAddResume();   
  }

  this.getAddResume = () => {
    this.addResumeList.workerId = id;
    $http.post(`${SERVER_CONTEXT}/api/safesite/workerResume/insertSelective`,
      this.addResumeList).
      then((resp) => {
        if (resp.data.success) {
          layer.msg(resp.data.message);
          this.isAddResume = false;
          this.resumeItemList.push(this.addResumeList);            
          this.addResumeList = {};
          this.workerInfoInit();
        } else {
          layer.alert(resp.data.message);
        }               
    });
  }

  // 取消增加简历
  this.cancelAddResume = () => {
    this.isAddResume = false;
    this.addResumeList = {};
  };

  // 初始化页面方法
  this.initPage = () => {
    this.workerInfoInit(); //获取人员详情-基本信息、专业技术、简历

    this.workerInfoTechInit(); // 获取教育培训
    this.educationTopicsList(); // 获取教育培训主题

    this.workerInfoSafeInit(); // 获取安全技术交底 分布分项
    this.workerInfoWorkerInit(); // 获取安全技术交底 工种
    this.safetyTechnicalDisclosure();  // 获取安全技术交底-分布分项-主题
    this.safetyWorkerTitle(); // 获取安全技术交底-工种-主题
    this.typeofWork = false; // 显示分布分项

    // 获取岗位类别
    this.getJobCategory();

    // 获取作业类别
    this.getWorkCategory();

    // 回到页面顶部
    this.goTop();

  }

  this.goTop = () => {
    $('html, body').animate({                 //添加animate动画效果  
         scrollTop: 0  
    }, 500);
  }

  this.initPage();

}

export default workerInfoDetailCtrl;